package com.t9101DR.dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;




public class BaseDao {
	private static String className="com.mysql.cj.jdbc.Driver";
	private static String url="jdbc:mysql://localhost:3306/dr?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
	private static String username="root";
	private static String pwd="202113";
	private Connection conn=null;
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getConnection() {
		try {
			if(conn==null||conn.isClosed()) {
				Class.forName(className);
				conn=DriverManager.getConnection(url,username,pwd);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch blocks
			e.printStackTrace();
		}
		return conn;
	}
	public void closeAll(Connection conn,Statement stmt,ResultSet rs) {
		try {
			if(conn!=null) {
				conn.close();
			}
			if(stmt!=null) {
				stmt.close();
			}
			if(rs!=null) {
				rs.close();
			}		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 增删改通用说法
	 * @param psql 预编译的sql，可能有？，有可能没有？
	 * @param params 参数的数组,需要和qsal中的?数量,个数,顺序一致
	 * @return 受影响的行数
	 */
	public int executeUpdate(String psql,Object[] params) {
		int count =0;
		PreparedStatement pstmt=null;
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(psql);
			if(params!=null&&params.length>0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);
				}
			}
			count=pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, null);
		}
		return count;
	}
}
